import { Form, Input, Button, Card, message, Icon, Col, Row } from 'antd';
import React, { useState, useEffect } from "react";
import { verifyAccount, sendEmailVerificationCode, resetPasswordByEmailVerificationCode } from "@/services/user";
import ywzdlogo from "@/assets/ywzdlogo.png";
import ywzd from "@/assets/ywzd.png";
import { formatMessage } from "umi-plugin-react/locale";
import styles from "./resetPassword.less";
const formItemLayout = {
    labelCol: { span: 4 },
    wrapperCol: { span: 18 },
};
class ResetPassword extends React.Component {
    state = {
        type: "account",
        id: undefined,
        emailDisabled: true,
        email: "",
        userFlag: "",
        verificationCode: "",
        //     计时器
        timer: null,
        resetPassCountdown:0,
        countdown: 0,
        step: 0
    };


    check = () => {
        this.props.form.validateFields((error, values) => {
            if (!error) {
                this.verifyAccountFun(values);
            }
        });

    };

    verifyAccountFun = async (value) => {
        let result = await verifyAccount(value, { 'username': value });
        if (result.code !== -1) {
            message.info("查询用户成功，请通过邮箱验证找回密码")

            this.setState({ email: result.email })
            this.setState({ id: result.id })
            this.setState({ userFlag: result.userFlag })
            this.setState({step:1})
        }

    }
    sendCode = async () => {
        // 设置定时器，每秒调用一次 countdown 函数
        // 如果已经在倒计时，则不执行任何操作
        const { countdown } = this.state;
        if (countdown > 0) return;

        // 设置倒计时时间（秒）
        const countdownTime = 60;
        this.setState({ countdown: countdownTime });
        if (this.state.timer) {
            clearInterval(this.state.timer);
        }
        const timer = setInterval(() => {
            this.setState(prevState => ({
                countdown: prevState.countdown - 1,
            }), () => {
                // 当倒计时结束时清除定时器并重置按钮
                if (this.state.countdown <= 0) {
                    clearInterval(this.state.timer);
                    this.setState({ timer: null, countdown: 0 });
                }
            });

        }, 1000)
        this.setState({ timer });

        let params = {
            "id": this.state.id,
            "userFlag": this.state.userFlag
        }
        let result = await sendEmailVerificationCode(params)
        if (result.code !== -1) {
            message.info("验证码已发送至邮箱，请注意查收")
        }
    };

    componentWillUnmount() {
        if (this.state.timer) {
            clearInterval(this.state.timer);
        }
    }
    resetPass = () => {
        const reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,20}$/;
        const {history} = this.props
        const { resetPassCountdown } = this.state;
        if (resetPassCountdown > 0) return;
        this.props.form.validateFields((error, values) => {
            if (!error) {
                // 设置倒计时时间（秒）
                const countdownTime = 3;
                this.setState({ resetPassCountdown: countdownTime });
                if (this.state.timer) {
                    clearInterval(this.state.timer);
                }
                const timer = setInterval(() => {
                    this.setState(prevState => ({
                        resetPassCountdown: prevState.resetPassCountdown - 1,
                    }), () => {
                        // 当倒计时结束时清除定时器并重置按钮
                        if (this.state.resetPassCountdown <= 0) {
                            clearInterval(this.state.timer);
                            this.setState({ timer: null, resetPassCountdown: 0 });
                        }
                    });

                }, 1000)
                this.setState({ timer });
                let params = {
                    "id": this.state.id,
                    "userFlag": this.state.userFlag,
                    "verificationCode": values.verificationCode,
                    "newPassword": values.newPassword,
                }
                resetPasswordByEmailVerificationCode(params).then((result) => {
                    if (result.code !== -1) {
                        message.success("重置密码成功")
                        history.push('/user/login')
                    }
                })
            }
        });
    }

    checkFieldForPassword(rule, value, callback) {
        const reg = /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,20}$/;
        if (rule.field === 'newPassword') {
            if (value) {
                if (reg.test(value)) {
                    if (value.length > 30 || value.length < 6) {
                        callback('只可填入8-20位数字和字母组合');
                    } else {
                        callback();
                    }
                } else {
                    callback('只可填入8-20位数字和字母组合');
                }
            } else {
                callback('只可填入8-20位数字和字母组合');
            }
        }
    }


    render() {
        const { getFieldDecorator } = this.props.form;
        const { history, form } = this.props;
        const { step } = this.state
        return (
            <div >
                <div style={{
                    display: "flex",
                    justifyContent: 'center',
                    alignItems: 'center',
                    height: "100%",
                    width: "100%",

                }}>

                    <div style={{
                        width: '402px',
                        marginTop: '52px'
                    }}>
                        <div style={{ textAlign: 'center' }}> <img src={ywzd} style={{ height: 80, marginBottom: 20 }} /></div>

                        <div style={{
                            backgroundColor: 'white',
                            borderRadius: '5px',
                            padding:'10px 0 40px'
                        }}>
                            <div style={{ paddingTop: '10px', paddingLeft: '10px' }}>
                                <Icon type="left" />
                                <button style={{
                                    backgroundColor: 'transparent',
                                    border: 'none',
                                    cursor: 'pointer',
                                    transition: 'color 0.3s ease-in-out'
                                }}
                                    onClick={() => history.push('/user/login')}>
                                    登录
                                </button>
                            </div>
                            <div style={{ textAlign: 'center', padding: '0 10px' }}>
                                <div style={{
                                    fontSize: 20,
                                    textAlign: 'center',
                                    color: '#5E6C84',
                                    paddingBottom: '20px',
                                }}>找回密码</div>
                                <Form form={form} 
                                autoComplete="new-password"
                                key='resetpassword'>
                                    <Form.Item {...formItemLayout}  label="账号">
                                        {getFieldDecorator('username', {
                                            rules: [
                                                {
                                                    required: true,
                                                    message: '请输入账号',
                                                },
                                            ],
                                        })(<Input autoComplete={"off"}  disabled={step == 1} style={{ height: '40px'}} placeholder="请输入账号" />)}
                                    </Form.Item>
                                    {step != 0 &&<div>
                                        <div style={{
                                            textAlign: "left", paddingLeft: "20px",
                                            fontSize: "14px", fontVariant: "tabular-nums",
                                            color: "black", paddingBottom: "20px",
                                            whiteSpace: "pre"
                                        }}>邮箱 :      <strong>{this.state.email}</strong></div>
                                        <Form.Item {...formItemLayout} className={styles.required} label="验证码">

                                            <Row gutter={12}>
                                                <Col span={15}>
                                                    <Form.Item style={{marginBottom:0}}> 
                                                    {getFieldDecorator('verificationCode', {
                                                        rules: [
                                                            {
                                                                required: true,
                                                                message: '输入验证码',
                                                            },
                                                        ],
                                                    })(<Input style={{ height: '40px' }} placeholder="请输入6位数验证码" />)}
                                                    </Form.Item>
                                                </Col>
                                                <Col span={4}>
                                                    <Button
                                                        disabled={this.state.countdown > 0}
                                                        onClick={this.sendCode}
                                                        style={{ height: '40px' }}
                                                    >
                                                        {this.state.countdown > 0 ? `${this.state.countdown} 秒后重试` : '发送验证码'}
                                                    </Button>
                                                </Col>
                                            </Row>
                                        </Form.Item>

                                        <Form.Item {...formItemLayout} label="新密码">
                                            {getFieldDecorator('newPassword', {
                                                rules: [
                                                    {
                                                        required: true,
                                                        message: '请输入新密码',
                                                    },
                                                    { validator: this.checkFieldForPassword, }
                                                ],
                                            })(<Input.Password autoComplete="new-password"  style={{ height: '40px' }} placeholder="请输入新密码" />)}
                                        </Form.Item>
                                    </div>}
                                </Form>

                                {step ==0 &&<div style={{padding:'0 60px'}}><Button type="primary" style={{ background: "#0052CC",width:'100%' }} onClick={this.check}>
                                    下一步，验证身份
                                </Button></div>}
                               {step!= 0 &&<div style={{padding:'0 60px'}}> <Button disabled={this.state.resetPassCountdown > 0} type="primary" style={{ background: "#0052CC" ,width:'100%'}} onClick={this.resetPass}>
                                    确认修改
                                </Button></div>}
                            </div>

                        </div>
                    </div>
                    {/*<div style={{position:"absolute",bottom:10,left:"50%",transform:"translateX(-50%)",textAlign:"center"}}>*/}
                    {/*    <img src={ywzdlogo} style={{width:110}} />*/}
                    {/*    <div style={{color:"#0070C0",fontSize:"26px",letterSpacing:"13px",fontWeight:"bold",textAlign:"center",paddingLeft:13}}>AIOS</div>*/}
                    {/*</div>*/}
                </div>
            </div>

        );
    }
}

export default Form.create()(ResetPassword);